package com.heima.wemedia.service.impl;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.heima.common.constants.WemediaConstants;
import com.heima.common.exception.CustomException;
import com.heima.model.common.dtos.PageResponseResult;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.wemedia.dtos.WeNewsAuditPageDto;
import com.heima.model.wemedia.dtos.WmNewsAuditUpdateDto;
import com.heima.model.wemedia.dtos.WmNewsDto;
import com.heima.model.wemedia.dtos.WmNewsPageReqDto;
import com.heima.model.wemedia.pojos.WmMaterial;
import com.heima.model.wemedia.pojos.WmNews;
import com.heima.model.wemedia.pojos.WmNewsMaterial;
import com.heima.model.wemedia.pojos.WmUser;
import com.heima.model.wemedia.vos.WmNewsAuditVo;
import com.heima.utils.thread.ThreadLocalUtil;
import com.heima.wemedia.mapper.WmMaterialMapper;
import com.heima.wemedia.mapper.WmNewsMapper;
import com.heima.wemedia.mapper.WmNewsMaterialMapper;
import com.heima.wemedia.service.WmNewsAutoScanService;
import com.heima.wemedia.service.WmNewsService;
import com.heima.wemedia.service.WmNewsTaskService;
import com.heima.wemedia.service.WmUserService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.kafka.core.KafkaTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.*;
import java.util.stream.Collectors;


@Service
public class WmNewsServiceImpl extends ServiceImpl<WmNewsMapper, WmNews> implements WmNewsService {

    @Autowired
    private WmNewsMaterialMapper wmNewsMaterialMapper;

    @Autowired
    private WmMaterialMapper wmMaterialMapper;

    @Autowired
    private WmNewsAutoScanService wmNewsAutoScanService;

    @Autowired
    private WmNewsTaskService wmNewsTaskService;

    @Autowired
    private KafkaTemplate<String, String> kafkaTemplate;

    @Autowired
    private WmUserService wmUserService;

    @Autowired
    private WmNewsMapper wmNewsMapper;


    /**
     * 查询文章列表
     *
     * @param dto
     * @return
     */
    @Override
    @Transactional
    public ResponseResult findList(WmNewsPageReqDto dto) {
        //1.校验数据
        if (dto == null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }
        dto.checkParam();
        //2.查询
        //2.1设置分页
        IPage page = new Page(dto.getPage(), dto.getSize());
        //2.2设置过滤条件
        LambdaQueryWrapper<WmNews> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        if (dto.getChannelId() != null) {
            lambdaQueryWrapper.eq(WmNews::getChannelId, dto.getChannelId());
        }
        if (dto.getBeginPubDate() != null && dto.getEndPubDate() != null) {
            lambdaQueryWrapper.between(WmNews::getCreatedTime, dto.getBeginPubDate(), dto.getEndPubDate());
        }
        if (StringUtils.isNotEmpty(dto.getKeyword())) {
            lambdaQueryWrapper.like(WmNews::getTitle, dto.getKeyword());
        }
        if (dto.getStatus() != null) {
            lambdaQueryWrapper.eq(WmNews::getStatus, dto.getStatus());
        }
        lambdaQueryWrapper.eq(WmNews::getUserId, ThreadLocalUtil.get());
        lambdaQueryWrapper.orderByDesc(WmNews::getCreatedTime);
        page = page(page, lambdaQueryWrapper);
        PageResponseResult pageResponseResult = new PageResponseResult(dto.getPage(), dto.getSize(), (int) page.getTotal());
        return pageResponseResult.ok(page.getRecords());
    }

    //将异步变同步，解决线程事务延迟更新数据库的问题
//    public ResponseResult submit(WmNewsDto wmNewsDto){
//        //先调用文章提交
//        ResponseResult responseResult = submitNews(wmNewsDto);
//        //异步调用：文章自动审核
//        if (responseResult.getData() != null){
//            wmNewsAutoScanService.autoScanWmNews((Integer) responseResult.getData());
//        }
//        responseResult.setData(null);
//        return responseResult;
//    }

    /**
     * 文章提交
     *
     * @param wmNewsDto
     * @return
     */
    @Transactional
    public ResponseResult submit(WmNewsDto wmNewsDto) {
        //1.校验数据
        if (wmNewsDto == null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }
        //2.处理数据
        WmNews wmNews = new WmNews();
        BeanUtils.copyProperties(wmNewsDto, wmNews);
        //2.1处理时间
        wmNews.setSubmitedTime(new Date());
        //2.2处理用户
        wmNews.setUserId(ThreadLocalUtil.get());
        //2.3处理内容图片集合
        List<String> contentImages = getConetentImages(wmNewsDto);
        //2.4处理type和封面图片
        List<String> coverImages = getCoverImages(contentImages, wmNewsDto, wmNews);
        //3 落库
        saveOrUpdateNews(wmNews);
        //4.草稿：直接返回结果
        if (wmNewsDto.getStatus() == WmNews.Status.NORMAL.getCode()) {
            return ResponseResult.okResult(AppHttpCodeEnum.SUCCESS);
        }
        //5.审核：插入关系表
        bindImagesAndNews(contentImages, wmNews.getId(), WmNewsMaterial.Type.ILLUSTRATION.getCode());
        bindImagesAndNews(coverImages, wmNews.getId(), WmNewsMaterial.Type.COVER.getCode());

        wmNewsTaskService.addNewsToTask(wmNews.getId(), wmNews.getPublishTime());

        return ResponseResult.okResult(wmNews.getId());
    }

    /**
     * 插入关系表
     *
     * @param images
     * @param userId
     * @param type
     */
    private void bindImagesAndNews(List<String> images, Integer userId, short type) {
        if (images == null || images.size() == 0) {
            return;
        }
        List<WmMaterial> wmMaterials = wmMaterialMapper.selectList(Wrappers.<WmMaterial>lambdaQuery().in(WmMaterial::getUrl, images));
        List<String> distinctImages = images.stream().distinct().collect(Collectors.toList());
        if (wmMaterials == null || wmMaterials.size() != distinctImages.size()) {
            throw new CustomException(AppHttpCodeEnum.DATA_NOT_EXIST);
        }
        List<Integer> idList = wmMaterials.stream().map(WmMaterial::getId).collect(Collectors.toList());
        wmNewsMaterialMapper.saveNewsAndMaterial(idList, userId, type);
    }

    /**
     * 落库
     *
     * @param wmNews
     */
    private void saveOrUpdateNews(WmNews wmNews) {
        if (wmNews.getId() != null) {
            //更新
            //清除以前的关系库
            wmNewsMaterialMapper.delete(Wrappers.<WmNewsMaterial>lambdaQuery().eq(WmNewsMaterial::getNewsId, wmNews.getId()));
            //落库
            updateById(wmNews);
        } else {
            wmNews.setCreatedTime(new Date());
            wmNews.setEnable(WmNews.EnableEnum.SHELVES.getCode());
            save(wmNews);
        }
    }

    /**
     * 处理type和封面图片
     *
     * @param contentImages
     * @param wmNewsDto
     * @param wmNews
     * @return
     */
    private List<String> getCoverImages(List<String> contentImages, WmNewsDto wmNewsDto, WmNews wmNews) {
        List<String> coverImages = wmNewsDto.getImages();
        if (wmNewsDto.getType() == WmNews.TypeEnum.AUTO.getCode()) {
            wmNews.setType(WmNews.TypeEnum.NO.getCode());
            if (contentImages != null && contentImages.size() >= WmNews.TypeEnum.ONE.getCode()) {
                if (contentImages.size() >= WmNews.TypeEnum.MORE.getCode()) {
                    wmNews.setType(WmNews.TypeEnum.MORE.getCode());
                    coverImages = contentImages.stream().limit(WmNews.TypeEnum.MORE.getCode()).collect(Collectors.toList());
                } else {
                    wmNews.setType(WmNews.TypeEnum.ONE.getCode());
                    coverImages = contentImages.stream().limit(WmNews.TypeEnum.ONE.getCode()).collect(Collectors.toList());
                }
            }
        }
        if (coverImages != null && coverImages.size() > 0) wmNews.setImages(StringUtils.join(coverImages, ","));
        return coverImages;
    }

    /**
     * 处理内容图片
     *
     * @param wmNewsDto
     * @return
     */
    private List<String> getConetentImages(WmNewsDto wmNewsDto) {
        if (wmNewsDto.getContent() == null) {
            return null;
        }
        /*parseArray：通用用法，转换成JSONArray*/
//            JSONArray objects = JSON.parseArray(wmNewsDto.getContent());
//            for (Object object : objects) {
//                JSONObject map = JSON.parseObject(object.toString());
////                Map<String, String> map = (Map) object;
//                if (map.get("type").equals("image")) {
//                    illustrationList.add(map.get("value").toString());
//                }
//            }
        /*parseArray：直接转换成Map*/
        List<Map> maps = JSON.parseArray(wmNewsDto.getContent(), Map.class);
        List<String> contentImages = new ArrayList<>();
        for (Map<String, String> map : maps) {
            if (map.get("type").equals("image")) {
                contentImages.add(map.get("value"));
            }
        }
        return contentImages;
    }


    /**
     * 文章回显
     *
     * @param id
     * @return
     */
    @Override
    public ResponseResult findOne(Integer id) {
        return ResponseResult.okResult(getOne(Wrappers.<WmNews>lambdaQuery().eq(WmNews::getId, id)));
    }

    /**
     * 删除功能
     * @param id
     * @return
     */
    @Override
    public ResponseResult deleteOne(Integer id) {
        WmNews wmNews = getById(id);
        if (wmNews != null && wmNews.getEnable() == WemediaConstants.WM_NEWS_ENABLE) {
            return ResponseResult.errorResult(AppHttpCodeEnum.STATUS_NOT_ALLOW, "文章上架中，无法删除，请先下架");
        }
        removeById(id);
        wmNewsMaterialMapper.delete(Wrappers.<WmNewsMaterial>lambdaQuery().eq(WmNewsMaterial::getNewsId, id));
        return ResponseResult.okResult(AppHttpCodeEnum.SUCCESS);
    }

    /**
     * 上下架功能
     * @param wmNewsDto
     */
    @Override
    public ResponseResult downOrUp(WmNewsDto wmNewsDto) {
        //校验数据
        if (wmNewsDto == null || wmNewsDto.getId() == null || wmNewsDto.getEnable() == null || wmNewsDto.getEnable() < 0 || wmNewsDto.getEnable() > 1) {
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }

        //修改文章状态
        //获取文章
        WmNews wmNews = getById(wmNewsDto.getId());
        if (wmNews == null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.DATA_NOT_EXIST);
        }
        //判断是否已发布
        if (!wmNews.getStatus().equals(WmNews.Status.PUBLISHED.getCode())) {
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID, "文章为发布，未能上下架");
        }

        update(Wrappers.<WmNews>lambdaUpdate().eq(WmNews::getId, wmNewsDto.getId())
                .set(WmNews::getEnable, wmNewsDto.getEnable()));

        if (wmNews.getArticleId() != null) {
            Map<String, Object> map = new HashMap<>();
            map.put("articleId", wmNews.getArticleId());
            map.put("enable", wmNewsDto.getEnable());
            kafkaTemplate.send(WemediaConstants.WM_NEWS_UP_OR_DOWN_TOPIC, JSON.toJSONString(map));
            return ResponseResult.okResult(AppHttpCodeEnum.SUCCESS);
        }
        return null;
    }

    /**
     * 文章审核列表查询
     * @param dto
     * @return
     */
    @Override
    public ResponseResult auditList(WeNewsAuditPageDto dto) {
        if (dto == null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }

        dto.checkParam();

        IPage page = new Page(dto.getPage(), dto.getSize());

        LambdaQueryWrapper<WmNews> lambdaQueryWrapper = new LambdaQueryWrapper();
        if (StringUtils.isNotEmpty(dto.getTitle())) {
            lambdaQueryWrapper.like(WmNews::getTitle, dto.getTitle());
        }
        if (dto.getStatus() != null) {
            lambdaQueryWrapper.eq(WmNews::getStatus, dto.getStatus());
        }
        lambdaQueryWrapper.orderByDesc(WmNews::getCreatedTime);

        page(page, lambdaQueryWrapper);

        PageResponseResult responseResult = new PageResponseResult(dto.getPage(), dto.getSize(), (int) page.getTotal());

        List<WmNewsAuditVo> wmNewsAuditVoList = new ArrayList<>();
        List<WmNews> records = page.getRecords();
        for (WmNews wmNews : records) {
            WmUser wmUser = wmUserService.getById(wmNews.getUserId());
            WmNewsAuditVo wmNewsAuditVo = new WmNewsAuditVo();
            BeanUtils.copyProperties(wmNews,wmNewsAuditVo);
            wmNewsAuditVo.setAuthorName(wmUser.getName());
            wmNewsAuditVoList.add(wmNewsAuditVo);
        }
        return responseResult.ok(wmNewsAuditVoList);
    }

    /**
     * 查看审核文章内容详情
     *
     * @param id
     * @return
     */
    @Override
    public ResponseResult auditDetail(Integer id) {
        WmNews wmNews = getById(id);
        WmNewsAuditVo wmNewsAuditVo = new WmNewsAuditVo();
        BeanUtils.copyProperties(wmNews,wmNewsAuditVo);
        WmUser wmUser = wmUserService.getById(wmNews.getUserId());
        wmNewsAuditVo.setAuthorName(wmUser.getName());
        return ResponseResult.okResult(wmNewsAuditVo);
    }

    /**
     * 文章人工审核结果
     * @param dto
     * @return
     */
    @Override
    public ResponseResult authUpdate(WmNewsAuditUpdateDto dto) {
        if (dto == null || dto.getId() == null){
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }
        WmNews wmNews = getById(dto.getId());
        if (wmNews.getStatus() != WmNews.Status.ADMIN_AUTH.getCode()){
            return ResponseResult.errorResult(AppHttpCodeEnum.DATA_EXIST,"文章状态不是待人工审核，请核实");
        }
        wmNews.setStatus(dto.getStatus());
        if (dto.getStatus() == WmNews.Status.FAIL.getCode()) wmNews.setReason(dto.getMsg());
        updateById(wmNews);

        wmNewsAutoScanService.publishNews(wmNews);

        return ResponseResult.okResult(AppHttpCodeEnum.SUCCESS);
    }

    /**
     * 判断频道ID是否被引用
     * @param channelId
     * @return
     */
    @Override
    public Integer existOfChannel(Integer channelId) {
        return wmNewsMapper.existOfChannel(channelId);
    }
}
